package com.yunchao.feature.base.presentation.ext

import android.content.Context
import android.os.SystemClock
import android.text.Editable
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.View
import android.view.View.GONE
import android.view.View.INVISIBLE
import android.view.View.VISIBLE
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.SearchView
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.LifecycleCoroutineScope
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

fun View.setDebouncedClickListener(interval: Long = 1000L, onClick: (View) -> Unit) {
    var lastClickTime = 0L

    setOnClickListener {
        val currentTime = System.currentTimeMillis()
        if (currentTime - lastClickTime >= interval) {
            lastClickTime = currentTime
            onClick(it)
        }
    }
}


var View.visible
    get() = visibility == VISIBLE
    set(value) {
        visibility = if (value) VISIBLE else GONE
    }

fun View.hide(gone: Boolean = true) {
    visibility = if (gone) GONE else INVISIBLE
}

fun View.show() {
    visibility = VISIBLE
}

// 创建一个扩展函数，用于创建只需要实现 afterTextChanged 方法的 TextWatcher
fun afterTextChanged(listener: (String) -> Unit): TextWatcher {
    return object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
        override fun afterTextChanged(s: Editable?) {
            s?.let {
                listener(it.toString())
            }
        }
    }
}


@OptIn(FlowPreview::class)
fun EditText.initSearchBehaviour(
    scope: LifecycleCoroutineScope,
    minimumTextCount: Int,
    delayMs: Long,
    onQueryTextChanged: SearchView.OnQueryTextListener,
) {
    scope.launch {
        callbackFlow {
            val watcher = this@initSearchBehaviour.addTextChangedListener {
                val query = it?.toString() ?: return@addTextChangedListener
                if (query.count() >= minimumTextCount) {
                    this.trySend(query)
                } else {
                    this.trySend(null)
                }
            }
            awaitClose {
                this@initSearchBehaviour.removeTextChangedListener(watcher)
            }
        }.distinctUntilChanged().debounce(delayMs).collectLatest {
            withContext(scope.coroutineContext) {
                onQueryTextChanged.onQueryTextChange(it)
            }
        }
    }
    this.setOnEditorActionListener { _, keyCode, keyEvent ->
        return@setOnEditorActionListener if (keyCode == EditorInfo.IME_ACTION_SEARCH || keyEvent.keyCode == KeyEvent.KEYCODE_ENTER) {
            onQueryTextChanged.onQueryTextSubmit(this.text?.toString())
            true
        } else {
            false
        }
    }
}

fun View.showKeyboard(): Boolean {
    this.requestFocus()
    val inputMethodManager: InputMethodManager? =
        context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
    return inputMethodManager?.showSoftInput(this, 0) == true
}

fun View.hideKeyboard(): Boolean {
    this.clearFocus()
    val inputMethodManager: InputMethodManager? =
        context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
    return inputMethodManager?.hideSoftInputFromWindow(this.windowToken, 0) == true
}
